<?php
declare(strict_types=1);
/**
 * Grace is committed to providing solutions for quickly building web applications
 * Please view the LICENSE file that was distributed with this source code,
 * For the full copyright and license information.
 * Thank you very much for using Grace.
 *
 * @Author kiki
 * @Link   https://gitee.com/kikigoper/grace
 */

namespace App\Erp\Mapper;

use App\Erp\Model\ErpGoodsType;
use Hyperf\Database\Model\Builder;
use Mine\Abstracts\AbstractMapper;

/**
 * 商品类别Mapper类
 */
class ErpGoodsTypeMapper extends AbstractMapper
{
    /**
     * @var ErpGoodsType
     */
    public $model;

    public function assignModel()
    {
        $this->model = ErpGoodsType::class;
    }

    /**
     * 获取前端选择树
     * @return array
     */
    public function getSelectTree(): array
    {
        return $this->model::query()
            ->select(['id', 'parent_id', 'id AS value', 'name AS label'])
            ->get()->toTree();
    }


    /**
     * 查询树名称
     * @param array|null $ids
     * @return array
     */
    public function getTreeName(array $ids = null): array
    {
        return $this->model::withTrashed()->whereIn('id', $ids)->pluck('name')->toArray();
    }

    /**
     * @param int $id
     * @return bool
     */
    public function checkChildrenExists(int $id): bool
    {
        return $this->model::withTrashed()->where('parent_id', $id)->exists();
    }

    /**
     * 搜索处理器
     * @param Builder $query
     * @param array $params
     * @return Builder
     */
    public function handleSearch(Builder $query, array $params): Builder
    {
        
        // 名称
        if (isset($params['name']) && $params['name'] !== '') {
            $query->where('name', '=', $params['name']);
        }

        // 创建时间
        if (isset($params['created_at'][0]) && isset($params['created_at'][1])) {
            $query->whereBetween('created_at', [$params['created_at'][0], $params['created_at'][1]]);
        }

        return $query;
    }
}